import { CanvasTexture, MeshBasicMaterial, PlaneGeometry } from "three";
import { Mesh } from "three/src/objects/Mesh";
import { App, Point } from "../../../../Docs";

export default class ElectricLabel2{
    private app;
    private param;
    private plane;
    private darwContext;
    private canvasWidth = 400;
    private canvasHeight = 360;

    constructor(param){
        this.app = App.getInstance();
        this.param = param;

        this.init();
    }

    private init(){
        // const position = new Point(120.2323057372291, 30.331910661137568, 0, '4326').toEPSGWeb();
        const position = this.param.position.toEPSGWeb();
        let geometryWidth = 300;
        let geometryHeight = 300;
        const geometry = new PlaneGeometry( geometryWidth, geometryHeight );
        const material = new MeshBasicMaterial({transparent: true}); //{color: 0xffff00}
        this.plane = new Mesh( geometry, material );
        this.plane.position.copy(position);
        this.app.add( this.plane );

        let drawingCanvas = document.createElement('canvas');
        drawingCanvas.width = this.canvasWidth;
        drawingCanvas.height = this.canvasHeight;
        this.darwContext=drawingCanvas.getContext('2d');

        this.fillCanvas(this.darwContext);

        material.map = new CanvasTexture(drawingCanvas);
    }

    private comupteTextHeight(ctx, text){
        let metrics = ctx.measureText(text);
        let height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
        return height;
    }

    private fillCanvas(ctx){
        ctx.globalAlpha = 0.0; // 完全透明
        ctx.clearRect(0,0,this.canvasWidth, this.canvasHeight);
        ctx.fillStyle='#00BFFF';
        // ctx.fillStyle = 'rgba(0, 0, 0, 0)'; 
        ctx.fillRect(0,0,this.canvasWidth, this.canvasHeight);

        ctx.globalAlpha = 1; // 不透明
        let fontSize = this.param.fontSize ? this.param.fontSize : 60;
        ctx.font= fontSize + "px Georgia";
        ctx.fillStyle = '#FFFFFF'; //'#FF4500';
        ctx.textAlign = "center"; // 水平居中对齐
        ctx.textBaseline = "top"; // 垂直中线对齐[5,7](@ref)
        let text = this.param.labelValue;
        ctx.fillText(text,this.canvasWidth/2,20);

        text = this.param.realValue ? this.param.realValue : '';
        let height = this.comupteTextHeight(ctx, text);
        let fontColor = this.param.fontColor ? this.param.fontColor : '#00BFFF';
        ctx.fillStyle = fontColor;
        ctx.fillText(text, this.canvasWidth/2, height+60);

        // text = "电阻: " + this.param.resistance;
        // height += this.comupteTextHeight(ctx, text);;
        // ctx.fillText(text, 60, height+120);
    }

    public updateContent(param){
        //把param中的数据覆盖到this.param中
        Object.assign(this.param, param);

        // const position = this.param.position.toEPSGWeb();
        // this.plane.position.copy(position);

        this.fillCanvas(this.darwContext);
        this.plane.material.map.needsUpdate = true;
    }
}